<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号" prop="validCertificateNumber">
        <el-input
          v-model="queryParams.validCertificateNumber"
          placeholder="请输入证件号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rural:ruralUser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rural:ruralUser:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rural:ruralUser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['rural:ruralUser:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruralUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="用户性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="手机号" align="center" prop="phonenumber" />
      <el-table-column label="有效证件类型" align="center" prop="validDocumentsType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.certificate_type" :value="scope.row.validDocumentsType"/>
        </template>
      </el-table-column>
      <el-table-column label="证件号" align="center" prop="validCertificateNumber" />
      <el-table-column label="用户类型" align="center" prop="userType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_type" :value="scope.row.userType"/>
        </template>
      </el-table-column>
      <el-table-column label="居住房屋" align="center" prop="ruralHouseId" :formatter="ruralHouseFormatter"  />
      <el-table-column label="现居城市" align="center" prop="currentCity" :formatter="currentCityFormatter"  />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rural:ruralUser:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rural:ruralUser:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" style="width:380px" placeholder="请选择性别">
            <el-option
              v-for="dict in dict.type.sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="有效证件类型" prop="validDocumentsType">
          <el-select v-model="form.validDocumentsType" style="width:380px" placeholder="请选择有效证件类型">
            <el-option
              v-for="dict in dict.type.certificate_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="证件号" prop="validCertificateNumber">
          <el-input v-model="form.validCertificateNumber" placeholder="请输入证件号" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="form.userType" style="width:380px" placeholder="请选择用户类型">
            <el-option
              v-for="dict in dict.type.user_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="居住房屋" prop="ruralHouseId">
          <el-select v-model="form.ruralHouseId" style="width:380px" placeholder="请选择居住房屋">
            <el-option
              v-for="ruralHouse in ruralHouseList"
              :key="ruralHouse.id"
              :label="ruralHouse.houseName"
              :value="ruralHouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="现居城市" prop="currentCity">
          <el-cascader
            size="large"
            style="width:380px"
            :options="options"
            v-model="form.currentCity"
            placeholder="请选择现居城市"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRuralUser, getRuralUser, delRuralUser, addRuralUser, updateRuralUser } from "@/api/rural/ruralUser";
import { listRuralHouse } from "@/api/rural/ruralHouse";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";

export default {
  name: "RuralUser",
  dicts: ['certificate_type','sex','user_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      ruralUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        sex: null,
        email: null,
        phonenumber: null,
        validDocumentsType: null,
        validCertificateNumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
        ],
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        phonenumber: [
            { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        validDocumentsType: [
            { required: true, message: '请选择有效证件类型', trigger: 'change' }
        ],
        validCertificateNumber: [
            { required: true, message: '请输入证件号', trigger: 'blur' }
        ],
        userType: [
            { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        ruralHouseId: [
            { required: true, message: '请选择居住房屋', trigger: 'change' }
        ],
        currentCity: [
            { required: true, message: '请选择现居城市', trigger: 'change' }
        ]
      },
      options: regionData,
      ruralHouseList: []
    };
  },
  created() {
    this.getList();
    listRuralHouse().then(response => {
        this.ruralHouseList = response.rows;
        console.log(response.rows)
    });
  },
  methods: {
    currentCityFormatter(row, column){
      if (row.currentCity != undefined){
        return row.currentCity.replaceAll(",","")
      }
      return ;
    },
    ruralHouseFormatter(row, column){
      for( let i = 0; i < this.ruralHouseList.length; i++){
        if(row.ruralHouseId === this.ruralHouseList[i].id){
          return this.ruralHouseList[i].houseName
        }
      }
    },
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listRuralUser(this.queryParams).then(response => {
        this.ruralUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        sex: null,
        email: null,
        phonenumber: null,
        validDocumentsType: null,
        validCertificateNumber: null,
        userType: null,
        currentCity: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        ruralHouseId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRuralUser(id).then(response => {
        this.form = response.data;
        if(this.form.currentCity != undefined){
          let currentCity = this.form.currentCity.split(",")
          this.form.currentCity = this.form.currentCity.split(",")
          console.log(this.form.currentCity )
          this.form.currentCity[0] = TextToCode[currentCity[0]].code
          console.log(this.form.currentCity )
          this.form.currentCity[1] = TextToCode[currentCity[0]][currentCity[1]].code
          console.log(this.form.currentCity )
          this.form.currentCity[2] = TextToCode[currentCity[0]][currentCity[1]][currentCity[2]].code
          console.log(this.form.currentCity )
        }
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let currentCity = this.form.currentCity
          for (let i = 0;i < currentCity.length; i++){
            currentCity[i] = CodeToText[currentCity[i]]
          }
          this.form.currentCity = currentCity.join(',')
          if (this.form.id != null) {
            updateRuralUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRuralUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户信息编号为"' + ids + '"的数据项？').then(function() {
        return delRuralUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rural/ruralUser/export', {
        ...this.queryParams
      }, `ruralUser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
